# coding=utf-8
import time

from apps.baselogic.handlers.qiniucloud import BaseHandler, check_expire_time, qiniuAuth, token_expire_time
from apps.open.share import app_logger
from django.http import JsonResponse


class Handler(BaseHandler):
    def __init__(self):
        BaseHandler.__init__(self, app_logger)

        self.METHOD_TAB = {
            'GET':  {
                'getuploadtoken': self.ajax_get_upload_token,
            }
        }

    def ajax_get_upload_token(self, request):
        """
        前端获取上传七牛需要的token
        """
        self.checkMandatoryParams(request, ['resource_type'])
        resource_type = request.param_dict['resource_type']
        keyprefix = 'stu_'

        curtime = time.time()
        if self.tokenTab[resource_type]:
            passedtime = curtime - self.lastGetTokenTimeTab[resource_type]
            # 没有过1小时，用缓存的token， 过了就重新生成token， 确保每次获取的token至少可以用24小时
            if passedtime < check_expire_time:
                self.app_logger.debug('passtime: %s, reuse saved token' % passedtime)
                return JsonResponse({'uptoken': self.tokenTab[resource_type]})

        # randomString = ''.join(random.choice(self.random_seeds) for i in range(6))
        self.tokenTab[resource_type] = qiniuAuth.upload_token(self.bucketTab[resource_type],
                                                              key=None,
                                                              expires=token_expire_time,
                                                              policy={
                                                   # 'callbackUrl':"http://wx.121866.com/qiniu/uploadcallback",
                                                   # 'callbackBody':"key=$(key)&name=$(fname)",  #$(etag)
                                                   # 'saveKey':'%s/$(year)$(mon)$(day)$(hour)$(min)$(sec)_$(etag)$(ext)'
                                                   # % keyprefix
                                                   'saveKey': '%s/$(etag)$(ext)' % keyprefix
                                               }
                                       )
        self.lastGetTokenTimeTab[resource_type] = curtime
        return JsonResponse({'uptoken': self.tokenTab[resource_type]})


qiniu_handler = Handler()
